const config = {
  BucketName: 'onelive', // 桶名称
  AccessKeyId: 'YIF2ERDVESNM8K1GQN4C', // 账号>我的凭证>访问密钥
  SecretKey: 'nJDRHkpFDzmj6wE5c4GtYt6KrkP3udQgfPFNThLP',
  EndPoint: `https://onelive.obs.cn-south-1.myhuaweicloud.com/`,
  upLoadUrl: `https://onelive.obs.cn-south-1.myhuaweicloud.com/`,
  timeout: 72 //这个是上传文件时Policy的失效时间 小时
}

const base64 = require('./base64.js');//Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - successc:成功回调
 *@param - types:图片或者视频
 *@param - failc:失败回调
 */ 
const uploadFile = function (filePath, types, successc, failc) {
  if (!filePath || filePath.length < 9) {
    uni.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  let date = new Date();
  date.setHours(date.getHours() + config.timeout);
  let srcT = date.toISOString();
  const path = `uniapp/headImg/${date.getTime() + Math.floor(Math.random() * 150) + types}`
  const policyEncoded = getPolicyEncode(srcT,config.BucketName,path)
  const signature = getSignature(policyEncoded,config.SecretKey)
  const upFormData = {
    key: path, // 储存路径
    AccessKeyId: config.AccessKeyId,
    Policy: policyEncoded,
    Signature: signature
  }
  
  uni.uploadFile({
    url: config.EndPoint,//开发者服务器 url
    filePath: filePath,//要上传文件资源的路径
    name: 'file',//必须填file
    formData: upFormData,
    success: function (res) {
			console.log(res);
      if (res.statusCode !== 204) {
        console.log("上传错误");
        return;
      }
      successc(config.upLoadUrl+path);
    },
    fail: function (err) {
      err.wxaddinfo = config.EndPoint;
      console.log(err);
    },
  })
}


//计算policy编码值
const getPolicyEncode = function (srcT,BucketName,site) {
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
        { bucket: BucketName }, //Bucket name
        { key: site }, // 格式 'xx/a.jpg' 路径/名称.格式 (路径选填)
    ]
  };

  const policyEncoded = base64.encode(JSON.stringify(policyText));
  return policyEncoded;
}

//利用SK计算Signature信息
const getSignature = function (policyEncoded, SecretKey) {
  const bytes = Crypto.HMAC(Crypto.SHA1, policyEncoded, SecretKey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
}

module.exports = uploadFile;